<template>
  <div>
    <el-dialog
      :model-value="visible"
      :title="data.id != '' ? '编辑' : '添加'"
      width="500"
      :close-on-click-modal="false"
      @close="cls"
    >
      <el-form ref="formData" :model="data">
        <el-form-item v-if="type != null" label="上级名称">
          <el-input v-model="data.parentName" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="data.dictName" />
        </el-form-item>
        <el-form-item v-if="type != null" label="表格类型">
          <el-select v-model="data.categoryType" placeholder="请选择">
            <el-option label="产品询价单" :value="1" />
            <el-option label="筛网询价模版" :value="2" />
            <el-option label="托辊询价模版" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cls">关闭</el-button>
          <el-button type="primary" @click="save"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { saveDict, updateDict } from "@/api/system/dict.js";
const data = ref({
  id: "",
  dictName: "",
  parentName: "",
  parentId: 0,
  categoryType: "",
  type: ""
});
const type = ref(null);
//定义组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: true
  },
  isSaver: {
    type: Boolean,
    default: true
  }
});

//同名引用
const formData = ref(null);
// const rules = reactive({
//   name: [{ required: true, message: "请输入部门名称", trigger: "blur" }]
// });

//定义事件
const emits = defineEmits(["close", "reflush"]);
function cls() {
  emits("close");
  emits("reflush");
}

//初始化方法，用于传参
function init(types, pid, pname, id, name, category) {
  if (types == "category") {
    type.value = types;
  } else {
    type.value = null;
  }

  data.value.type = types;
  if (id != undefined) {
    data.value.id = id;
    data.value.dictName = name;
  } else {
    data.value.dictName = "";
    data.value.id = undefined;
  }

  data.value.parentId = pid;
  data.value.parentName = pname;
  data.value.categoryType = category;
  if (pname == undefined) data.value.parentName = "无";
}
//暴露init方法，方便父组件调用
defineExpose({ init });

//保存
async function save() {
  const valid = formData.value.validate;
  if (!valid) return;
  let res = ref({});

  console.log("data>>>>>>>>>>", data.value);
  if (data.value.id == "" || data.value.id == undefined) {
    //发送数据
    res.value = await saveDict(data.value);
  } else {
    res.value = await updateDict(data.value);
  }
  if (res.value.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    });
    cls();
  }
}
</script>
<style scoped></style>
